<?php

namespace app\weixin\controller;

use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;
use think\Config;
use think\Controller;
use think\Request;
use think\Cookie;
use app\common\model\miniapp\MemberMiniapp as AuthorizerModel;

class platform extends Controller
{

    private $openPlatform;
    //全网发布时使用的测试账号，如果文档发生修改，直接修改这里的账号即可
    private $testData = [
        'officialAccount' => ['appid' => 'wx570bc396a51b8ff8', 'Username' => 'gh_3c884a361561'],
        'miniProgram'     => ['appid' => 'wxd101a85aa106f53e', 'Username' => 'gh_8dad206e9538'],
    ];
    public function __construct()
    {
        $platform_config = [
            'app_id'  => Config::get('platform.appid'),
            'secret'  => Config::get('platform.secret'),
            'token'   => Config::get('platform.token'),
            'aes_key' => Config::get('platform.encodingaeskey'),
        ];
       
        $this->openPlatform = Factory::openPlatform($platform_config);

    }
    /**
     * 接受component verify ticket
     *
     * @return string success
     * @author
     **/
    public function ticket()
    {
        $server = $this->openPlatform->server;
        return $server->serve();

    }
    /**
     * 接受消息，包含全网发布
     *
     * @return string success
     * @author
     **/
    public function message()
    {
        $server = $this->openPlatform->server;
        $server->push(function ($message) {
            //全网发布测试
            if ($message['ToUserName'] === $this->testData['officialAccount']['Username'] || $message['ToUserName'] === $this->testData['miniProgram']['Username']) {
                //全网发布测试1，服务器端返回信息
                if ('TESTCOMPONENT_MSG_TYPE_TEXT' === $message['Content']) {
                    return new Text('TESTCOMPONENT_MSG_TYPE_TEXT_callback');
                };
                //全网发布测试2，客服消息
                if (strpos($message['Content'], "QUERY_AUTH_CODE") > -1) {
                    $auth_code       = trim(str_replace("QUERY_AUTH_CODE:", "", $message['Content']));
                    $message         = new Text($auth_code . '_from_api');
                    $result          = $this->openPlatform->handleAuthorize($auth_code);
                    $appid           = $result['authorization_info']['authorizer_appid'];
                    $access_token    = $result['authorization_info']['authorizer_access_token'];
                    $refresh_token   = $result['authorization_info']['authorizer_refresh_token'];
                    $officialAccount = $this->openPlatform->officialAccount($appid, $refresh_token);
                    //$miniProgram     = $this->openPlatform->miniProgram($appid, $refresh_token);
                    $officialAccount->customer_service->message($message)->to($message['FromUserName'])->send();
                }
            } else {
                //小程序审核结果
                if ($message['MsgType'] == 'event') {
                    if ($message['Event'] == 'weapp_audit_success') {
                        //小程序审核通过
                        $AuthorizerModel = new AuthorizerModel();
                        $AuthorizerModel->save([
                            'status' => 3,
                        ], ['user_name' => $message['ToUserName']]);
                    }
                    if ($message['Event'] == 'weapp_audit_fail') {
                        //小程序审核失败
                        $AuthorizerModel = new AuthorizerModel();
                        $AuthorizerModel->save([
                            'status' => 4,
                            'error'  => $message['Reason'],
                        ], ['user_name' => $message['ToUserName']]);
                    }
                }
            }Ï;

        });
        return $server->serve();
    }
    /**
     * 跳转到授权页
     *
     * @return void
     * @author 
     **/
    public function jumpToAuthPage ()
    {
         //授权后回调URI
        $callback_uri=Request::instance()->domain().'/weixin/platform/getAuthorizerInfo';
        //授权URL
        $url=$this->openPlatform->getPreAuthorizationUrl($callback_uri);
        //跳转
        echo "<script language='javascript' type='text/javascript'>window.location.href = '$url'</script>";
    }
    /**
     * 获取授权方基本信息
     *
     * @return void
     * @author 
     **/
    public function getAuthorizerInfo()
    {
        $auth_code = $this->request->get('auth_code');
        $cookieToken = Cookie::get('memberID');
        $cookieInfo = authcode($cookieToken, 'DECODE');
        $member_id = substr($cookieInfo, 0, strpos($cookieInfo, '|'));
        if (empty($auth_code)) {
            $this->error('授权失败！');
        }
        $result=$this->openPlatform->handleAuthorize($auth_code);
        if (empty($result['authorization_info']['authorizer_appid'])) {
            $this->error('第三方授权失败,无法获取appid！');
         }
        $datas['authorizer_appid'] = $result['authorization_info']['authorizer_appid'];
        $AuthorizerModel = new AuthorizerModel();
        $auth = $AuthorizerModel->get(['authorizer_appid' => $datas['authorizer_appid'], 'member_id' => $member_id]);
        if (!empty($auth)) {
            $this->error('已经授权过了！');
        }

        $datas['authorizer_access_token'] = $result['authorization_info']['authorizer_access_token'];
        $datas['authorizer_refresh_token'] = $result['authorization_info']['authorizer_refresh_token'];
        $datas['authorizer_refresh_token_expir_time'] = time() + 7000;

        
        $result=$this->openPlatform->getAuthorizer($datas['authorizer_appid']);
        if (!empty($result['authorizer_info'])) {
            $datas['nick_name'] = $result['authorizer_info']['nick_name'];
            $datas['head_img'] = empty($result['authorizer_info']['head_img']) ? '' :$result['authorizer_info']['head_img'];
            $datas['user_name'] = $result['authorizer_info']['user_name'];
            $datas['qrcode_url'] = $result['authorizer_info']['qrcode_url'];
            $datas['principal_name'] = $result['authorizer_info']['principal_name'];
            $datas['signature'] = $result['authorizer_info']['signature'];
            $datas['member_id'] = $member_id;
            $datas['appkey'] = md5(uniqid());
            $AuthorizerModel = new AuthorizerModel();
            $AuthorizerModel->save($datas);
            $this->success('添加成功', url('/manage/miniappshop/index',['member_miniapp_id'=>$AuthorizerModel->member_miniapp_id]));
        }
        $this->error('授权失败');
    }
    

}
